//
//  LicenseVC.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/12/5.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "LicenseVC.h"
#import "TopBackView.h"
#import "Common.h"
#import "RootViewController.h"
#import "WKProgressHUD.h"
#import "NullView.h"
#import "CollectionViewCell.h"

@interface LicenseVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,strong) NullView *nullView;



@property (nonatomic,strong) NSMutableDictionary *dictionary;

@end

@implementation LicenseVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArray = [NSMutableArray array];
    self.dictionary = [NSMutableDictionary dictionary];
    
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"准驾车型"];
    
    
    [topBackView.rightButton addTarget:self action:@selector(confirmButton) forControlEvents:UIControlEventTouchUpInside];
    [topBackView.rightButton setTitle:@"完成" forState:UIControlStateNormal];
    topBackView.rightButton.titleLabel.font = Font(14);
    [topBackView.rightButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    
    
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBackView];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
    self.view.backgroundColor = GrayColor;
    self.nullView = [[NullView  alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight  - 60 * kHeight) andTitle:@"" andImage:[UIImage imageNamed:@"no_lines"]];
    self.nullView.backgroundColor = GrayColor;
    
    
    [self initDataSource];
    
    [self initCollectionView];
}

-(void)initDataSource
{
    
    NSString *urlString = [NSString stringWithFormat:@"%@licensetype/list?duserid=%@",Main_interface,self.did];
    [Common requestWithUrlString:urlString contentType:application_json finished:^(id responseObj) {
        
        if ([responseObj[@"data"] count] > 0) {
            
            self.dataArray = [NSMutableArray arrayWithArray:responseObj[@"data"]];
        }
        
        if (self.dataArray.count > 0) {
            for (int i = 0; i < self.dataArray.count; i ++) {
                
                [self.dictionary setObject:self.dataArray[i][@"isCheck"] forKey:[NSString stringWithFormat:@"%d",i]];

            }
        }
        
        
        [self.collectionView reloadData];
        
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
}

-(void)initCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(88 * kWidth, 30 * kHeight);
    layout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight - 64) collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    self.collectionView.backgroundColor = WhiteColor;
    self.collectionView.alwaysBounceVertical = YES;
    
    [self.collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"CollectionViewCell"];
    
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];
    
    [self.view addSubview:self.collectionView];
}


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    
    if (self.dataArray.count > 0) {
        
        return  self.dataArray.count;
        
    } else {
        return 0;
    }
    
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CollectionViewCell *cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionViewCell" forIndexPath:indexPath];
    cell.label.layer.borderWidth = 0.5;
    cell.label.layer.borderColor = LineGrayColor.CGColor;
    cell.label.font = Font(13);
    cell.label.layer.cornerRadius = 5 * kHeight;
    cell.label.layer.masksToBounds = YES;
    
    NSString *index = [NSString stringWithFormat:@"%ld",indexPath.row];
    
    if (self.dataArray.count > 0) {
        cell.label.text = self.dataArray[indexPath.row][@"licenseName"];
        
        if ([[self.dictionary objectForKey:index] boolValue]) {
            
            cell.label.backgroundColor = YellowColor;
            cell.label.textColor = WhiteColor;
            
        } else {
            cell.label.backgroundColor = WhiteColor;
            cell.label.textColor = BlackColor;
            
        }
    }
    
    return cell;
    
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqual:UICollectionElementKindSectionHeader]) {
        
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
        
        
        for (UILabel *view in headerView.subviews) {
            [view removeFromSuperview];
        }
        UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(14, 0, 200, headerView.frame.size.height)];
        lable.font = Font(14);
        lable.textColor = Color_RGB(14, 14, 14, 1);
        
        lable.text = @"请选择";
        headerView.backgroundColor = GrayColor;
        
        [headerView addSubview:lable];
        
        return headerView;
    } else {
        return nil;
    }
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(screenWidth, 40);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
//    NSArray *arr = [self.dictionary allValues];
//    int a = 0;
//    for (int i = 0; i < arr.count; i ++) {
//        
//        if ([arr[i] boolValue]) {
//            a++;
//        }
//        
//    }
//    
//    if (a >= 2) {
//        
//        [self showAlertController];
//        
//    } else {
    
    NSString *index = [NSString stringWithFormat:@"%ld",indexPath.row];
    
    if ([[self.dictionary objectForKey:index] boolValue]) {
        
        [self.dictionary setObject:@(NO) forKey:index];
        
    } else {
        [self.dictionary setObject:@(YES) forKey:index];
    }
    
    [self.collectionView reloadData];
//    }
}


-(void)showAlertController
{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"最多可以选择两种准驾车型" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}


-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:YES];
    
}

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)confirmButton
{
    
    
    NSArray *arr = [self.dictionary allValues];
        int a = 0;
        for (int i = 0; i < arr.count; i ++) {
    
            if ([arr[i] boolValue]) {
                a++;
            }
    
        }
    
        if (a > 2) {
    
            [self showAlertController];
            
        } else {
    
    NSMutableArray *arr = [NSMutableArray array];
    NSMutableArray *arr1 = [NSMutableArray array];

    for (int i = 0; i < [[self.dictionary allKeys] count]; i ++) {
        
        if ([[self.dictionary objectForKey:[NSString stringWithFormat:@"%d",i]]boolValue]) {
            
            [arr addObject:self.dataArray[i][@"id"]];
            
            [arr1 addObject:self.dataArray[i][@"licenseName"]];
            
        }
        
    }
    
    NSString *str = [arr componentsJoinedByString:@","];
    NSString *str1 = [arr1 componentsJoinedByString:@","];
    
    if (arr.count == 0) {
        [WKProgressHUD popMessage:@"驾照类型不能为空" inView:self.view duration:1.5 animated:YES];
    } else {
        
    if (self.callBack) {
        self.callBack(str,str1);
        
    }
    
    //延迟执行
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.navigationController popViewControllerAnimated:YES];
        
    });
        
    }
        }

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
